<template>
  <!-- 打印按钮 -->
  <svg aria-hidden="true" class="print w-6 h-6" @click="doPrint">
    <use xlink:href="#icon-print"/>
  </svg>

  <div v-loading="printLoading">
    <div id="printDom" class="bg-white">

      <!-- 循环打印患者报告 -->
      <div v-for="(info, index) in patientInfoArray" :key="index">

        <!-- 医院名称 -->
        <el-row class="p-2">
          <el-col class="hospital-name" :span="24">{{info.hospitalName}}</el-col>
          <el-col class="hospital-subtitle" :span="24">睡眠监测报告</el-col>
          <el-col class="report-time-txt" :span="24">报告日期：{{ reportDate }}</el-col>
        </el-row>
        <!-- 患者基本信息 开始 -->
        <div class="patDetails bg-white" style="page-break-inside:avoid;">
          <div class="detail-title">患者信息</div>
          <div class="info-items">
            <div class="info-items-label">姓<span>;;;;;;;;</span>名：</div>
            <div class="info-items-value">{{ info.patientName }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">就<span>;;</span>诊<span>;;</span>号：</div>
            <div class="info-items-value">{{ info.visitNoStr }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">身份证号：</div>
            <div class="info-items-value">{{ info.identityNumber }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">电<span>;;;;;;;;</span>话：</div>
            <div class="info-items-value">{{ info.phone }}</div>
          </div>

          <div class="info-items">
            <div class="info-items-label">出生日期：</div>
            <div class="info-items-value">{{ info.birthday }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">年<span>;;;;;;;;</span>龄：</div>
            <div class="info-items-value">{{ info.age ? info.age + '岁' : '-' }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">性<span>;;;;;;;;</span>别：</div>
            <div class="info-items-value">{{ info.gender ? (info.gender == '1' ? '男' : '女') : '' }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">入院诊断：</div>
            <div class="info-items-value">{{ info.diagnosis }}</div>
          </div>

          <div class="info-items" style="width: 100%">
            <div class="info-items-label">家庭地址：</div>
            <div class="info-items-value">{{ info.addr }}</div>
          </div>

          <div class="info-items">
            <div class="info-items-label">科<span>;;;;;;;;</span>室：</div>
            <div class="info-items-value">{{ info.deptName }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">床<span>;;</span>位<span>;;</span>号：</div>
            <div class="info-items-value">{{ info.bedNo }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">疗程天数：</div>
            <div class="info-items-value">{{ info.rentalDays + '天' }}</div>
          </div>

          <div class="info-items">
            <div class="info-items-label">记录时间：</div>
            <div class="info-items-value">{{ info.visitTime }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">截止时间：</div>
            <div class="info-items-value">{{ info.outTime }}</div>
          </div>
          <div class="info-items">
            <div class="info-items-label">设备编号：</div>
            <div class="info-items-value">{{ info.equipmentNo }}</div>
          </div>
        </div>
        <!-- 患者基本信息 结束 -->

        <!-- 睡眠 开始 -->
        <div class="report-title" v-if="printCheckList.find((val : any) => val == sleepLabel)" style="page-break-inside:avoid;">{{ serialNumber.sleep }}. 睡眠结构</div>
        <div v-if="printCheckList.find((val : any) => val == sleepLabel)" class="sleep-report" style="page-break-inside:avoid;">
          <div class="sleep-report-items">
            睡眠总时间：{{info.sleepChartData?.sleepDuration || ""}}
          </div>
          <div class="sleep-report-items">
            占记录总时间(%)：{{ info.sleepReportData[0]?.sleepTimeProp || "" }}
          </div>
          <div class="sleep-report-items">
            离床次数：{{info.sleepChartData?.getUpCount || ""}}
          </div>
          <div class="sleep-report-items">
            起床时间：{{info.sleepChartData?.wakeUpTimeStr || ""}}
          </div>
          <div class="sleep-report-items">
            无效记录时长：{{info.sleepChartData?.outBedDuration || ""}}
          </div>
          <div class="sleep-report-items">
            占记录总时间(%)：{{ info.sleepReportData[0]?.outBedTimeProp || "" }}
          </div>
          <div class="sleep-report-items">
            低通气(次)：{{info.spo2ChartData?.hypopneaTimes || "-"}}
          </div>
          <div class="sleep-report-items">
            呼吸暂停(次)：{{info.breatheChartData?.apneaTimes || "-"}}
          </div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == sleepLabel)" class="my-report-table">
          <div class="items">标题</div>
          <div class="items">睡眠时长</div>
          <div class="items">浅睡时长</div>
          <div class="items">深睡时长</div>
          <div class="items">清醒时长</div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == sleepLabel)"
             v-for="(obj, index) in info.sleepReportData" :key="index" class="my-report-table">
          <div class="items items-contents"
               :style="index === info.sleepReportData.length - 1? 'border-bottom: 1px solid #909399;' : ''">{{ obj.sleepTitle||'-' }}
          </div>
          <div class="items items-contents"
               :style="index === info.sleepReportData.length - 1? 'border-bottom: 1px solid #909399;' : ''">{{ obj.sleepTotal||'-' }}
          </div>
          <div class="items items-contents"
               :style="index === info.sleepReportData.length - 1? 'border-bottom: 1px solid #909399;' : ''">{{ obj.lightSleepDuration||'-' }}
          </div>
          <div class="items items-contents"
               :style="index === info.sleepReportData.length - 1? 'border-bottom: 1px solid #909399;' : ''">{{ obj.deepSleepDuration||'-' }}
          </div>
          <div class="items items-contents"
               :style="index === info.sleepReportData.length - 1? 'border-bottom: 1px solid #909399;' : ''">{{ obj.awakeDuration||'-' }}
          </div>
        </div>
        <!-- 睡眠 结束 -->

        <!-- 血氧饱和度 开始 -->
        <div v-if="printCheckList.find((val : any) => val == spo2Label)" class="report-title"
             style="page-break-inside:avoid;">{{ serialNumber.spo2 }}. 血氧饱和度（参考值为95%-100%）
        </div>
        <div v-if="printCheckList.find((val : any) => val == spo2Label)" class="my-report-table">
          <div class="items items25">标题</div>
          <div class="items items25">最高血氧</div>
          <div class="items items25">最低血氧</div>
          <div class="items items25">平均血氧</div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == spo2Label)" class="my-report-table">
          <div class="items items25 items-contents">{{ info.spo2ReportData[0]?.title || "%"}}</div>
          <div class="items items25 items-contents">{{ info.spo2ReportData[0]?.highestSpO2 || "-" }}</div>
          <div class="items items25 items-contents">{{ info.spo2ReportData[0]?.lowestSpO2 || "-" }}</div>
          <div class="items items25 items-contents">{{ info.spo2ReportData[0]?.avgSpO2 || "-" }}</div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == spo2Label)" class="my-report-table">
          <div class="items items25">程度</div>
          <div class="items items25">轻度(85%~90%)</div>
          <div class="items items25">中度(80%~84%)</div>
          <div class="items items25">重度(80%以下)</div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == spo2Label)" class="my-report-table">
          <div class="items items25 items-contents" style="border-bottom: 1px solid #909399;">{{ info.spo2ReportData[1]?.title || "次"}}</div>
          <div class="items items25 items-contents" style="border-bottom: 1px solid #909399;">{{ info.spo2ReportData[1]?.mildSpO2 || "-" }}</div>
          <div class="items items25 items-contents" style="border-bottom: 1px solid #909399;">{{ info.spo2ReportData[1]?.moderateSpO2 || "-" }}</div>
          <div class="items items25 items-contents" style="border-bottom: 1px solid #909399;">{{ info.spo2ReportData[1]?.severeSpO2 || "-" }}</div>
        </div>
        <!-- 血氧饱和度 结束 -->

        <!-- 心率 开始 -->
        <div v-if="printCheckList.find((val : any) => val == heartLabel)" class="report-title"
             style="page-break-inside:avoid;">{{ serialNumber.hr }}. 心率（参考值为50-100bpm）
        </div>
        <div v-if="printCheckList.find((val : any) => val == heartLabel)" class="my-report-table">
          <div class="items">标题</div>
          <div class="items">最大心率</div>
          <div class="items">最小心率</div>
          <div class="items">平均心率</div>
          <div class="items">静息基准心率</div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == heartLabel)"
             v-for="(obj, index) in info.heartReportData" :key="index" class="my-report-table">
          <div class="items items-contents items-bottom">{{ obj.title }}</div>
          <div class="items items-contents items-bottom">{{ obj.highestHeartRate||'-' }}</div>
          <div class="items items-contents items-bottom">{{ obj.lowestHeartRate||'-' }}</div>
          <div class="items items-contents items-bottom">{{ obj.avgHeartRate||'-' }}</div>
          <div class="items items-contents items-bottom">{{ obj.rheartRate||'-' }}</div>
        </div>
        <!-- 心率 结束 -->

        <!-- 呼吸 开始 -->
        <div v-if="printCheckList.find((val : any) => val == breatheLabel)" class="report-title"
             style="page-break-inside:avoid;">{{ serialNumber.breathe }}. 呼吸（参考值为14-24次/分钟）
        </div>
        <div v-if="printCheckList.find((val : any) => val == breatheLabel)" class="my-report-table">
          <div class="items">标题</div>
          <div class="items">平均呼吸</div>
          <div class="items">呼吸过缓</div>
          <div class="items">呼吸过速</div>
          <div class="items">呼吸小于等于5</div>
        </div>
        <div v-if="printCheckList.find((val : any) => val == breatheLabel)"
             v-for="(obj, index) in info.breatheReportData" :key="index" class="my-report-table">
          <div class="items items-contents items-bottom">{{ obj.title }}</div>
          <div class="items items-contents items-bottom">{{ obj.avgBreathRate||'-' }}</div>
          <div class="items items-contents items-bottom">{{ obj.lowestBreathRate||'-' }}</div>
          <div class="items items-contents items-bottom">{{ obj.highestBreathRate||'-' }}</div>
          <div class="items items-contents items-bottom">{{ obj.lessThanOrEqualFiveCount||'-' + '次' }}</div>
        </div>
        <div id="isPrintSwitch" style=" color: #E6A23C; font-size: 12px;">
          <el-icon> <WarningFilled/> </el-icon> 是否打印呼吸小于等于5次/分钟记录
          <el-switch v-model="is_print" size="small" active-text="是" inactive-text="否" style="margin-left: 30px;"/>
        </div>
        <div class="report-title" id="lessThanFiveTxt" v-if="printCheckList.find((val : any) => val == breatheLabel) && is_print"
             style="page-break-inside:avoid;">呼吸小于等于5次/分钟记录
        </div>
        <div id="lessThanFiveTitle" v-if="printCheckList.find((val : any) => val == breatheLabel) && is_print" class="my-report-table">
          <div class="items" style="width: 30%;">时间</div>
          <div class="items" style="width: 20%;">呼吸率</div>
          <div class="items" style="width: 15%;">血氧</div>
          <div class="items" style="width: 15%;">心率</div>
          <div class="items">体动状态</div>
        </div>
        <div id="lessThanFiveContents"
             v-if="printCheckList.find((val : any) => val == breatheLabel) && is_print && info.breatheReportData[0].breathLessThanFive.length <= 0"
             class="my-report-table">
          <div
            style="color: #909399; width: 100%; font-size: 14px; line-height: 50px; text-align: center; border: 1px solid #909399;">
            暂无数据！
          </div>
        </div>
        <div id="lessThanFiveContents"
             v-if="printCheckList.find((val : any) => val == breatheLabel) && is_print && info.breatheReportData[0].breathLessThanFive.length > 0"
             v-for="(obj, index) in info.breatheReportData[0].breathLessThanFive" :key="index" class="my-report-table">
          <div class="items items-contents"
               :style="(index === info.breatheReportData[0].breathLessThanFive.length - 1? 'border-bottom: 1px solid #909399;' : '') + 'width: 30%;'">
            {{ obj.acquisitionTime }}
          </div>
          <div class="items items-contents"
               :style="(index === info.breatheReportData[0].breathLessThanFive.length - 1? 'border-bottom: 1px solid #909399;' : '') + 'width: 20%;'">
            {{ obj.breathRate }}
          </div>
          <div class="items items-contents"
               :style="(index === info.breatheReportData[0].breathLessThanFive.length - 1? 'border-bottom: 1px solid #909399;' : '') + 'width: 15%;'">
            {{ obj.spo2 }}
          </div>
          <div class="items items-contents"
               :style="(index === info.breatheReportData[0].breathLessThanFive.length - 1? 'border-bottom: 1px solid #909399;' : '') + 'width: 15%;'">
            {{ obj.heartRate }}
          </div>
          <div class="items items-contents"
               :style="(index === info.breatheReportData[0].breathLessThanFive.length - 1? 'border-bottom: 1px solid #909399;' : '') + ''">
            {{ obj.bodyMove == "1"?"正常":"体动" }}
          </div>
        </div>
        <!-- 呼吸 结束 -->

        <!-- 建议 开始 -->
        <el-row style="page-break-inside:avoid;">
          <el-col :span="24" class="report-title">{{ serialNumber.sugg }}. 建议</el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="24">
                <textarea v-model="suggTxt"></textarea>
              </el-col>
            </el-row>
            <el-popover placement="left" :width="400" trigger="hover">
              <template #reference>
                <el-icon id="my-icon" class="my-icon"><ArrowDown/></el-icon>
              </template>
              <div class="sugg-datas">
                <div @click="getSugg" class="sugg-datas-item">心率平稳。</div>
                <div @click="getSugg" class="sugg-datas-item">呼吸率平稳。</div>
                <div @click="getSugg" class="sugg-datas-item">轻度失眠，以浅睡眠为主。</div>
                <div @click="getSugg" class="sugg-datas-item">中度失眠。</div>
                <div @click="getSugg" class="sugg-datas-item">心率过高睡眠不佳，出现心脏事件的概率提高。</div>
                <div @click="getSugg" class="sugg-datas-item">出现血氧进行性降低，怀疑出现呼吸窘迫综合征。</div>
                <div @click="getSugg" class="sugg-datas-item">呼吸暂停综合征。</div>
                <div @click="getSugg" class="sugg-datas-item">
                  患者出现嗜睡；呼吸出现呼吸急促，最后变为浅慢；心率波动大，由心率急剧加快到后续的减慢；出现血氧下降的表现。怀疑出现脑梗的情况。
                </div>
                <div @click="getSugg" class="sugg-datas-item">
                  黎明效应：睡眠不足，引起胰岛素抵抗，导致糖代谢紊乱，调节睡眠，降低升糖激素的活性，改善黎明现象，控制血糖。
                </div>
              </div>
            </el-popover>
          </el-col>
        </el-row>
        <!-- 建议 结束 -->

        <!-- 图表 -->
        <Sleep v-if="printCheckList.find((val : any) => val == sleepLabel)" :reportData="info.sleepChartData" :big-font-flag="true" class="mt-7"/>
        <SaO2 v-if="printCheckList.find((val : any) => val == spo2Label)" :reportData="info.spo2ChartData" :big-font-flag="true" class="mt-7"/>
        <Hr v-if="printCheckList.find((val : any) => val == heartLabel)" :reportData="info.heartChartData" :big-font-flag="true" class="mt-7"/>
        <Resp v-if="printCheckList.find((val : any) => val == breatheLabel)" :reportData="info.breatheChartData" :big-font-flag="true" class="mt-7"/>

        <div style="padding-left: 60%;">医师签名：</div>

        <div class="PageNext"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import {getMattressReportData} from "@/api/patientREG";
import {getDay} from "@/utils";
import printJS from "print-js";
import SaO2 from "@/views/Patient/components/BodyReport/saO2.vue";
import Resp from "@/views/Patient/components/BodyReport/resp.vue";
import Sleep from "@/views/Patient/components/BodyReport/sleep.vue";
import Hr from "@/views/Patient/components/BodyReport/hr.vue";
import {useCache} from "@/hooks/web/useCache";
import {ElMessageBox} from 'element-plus';
import {Base64} from 'js-base64';

const route = useRoute()
const sleepLabel: string = "sleep";
const spo2Label: string = "spo2";
const heartLabel: string = "heart";
const breatheLabel: string = "breathe";

const printLoading = ref(false);

/** 报告日期  */
const reportDate = getDay();
/** 报告项目  */
const printCheckList = ['sleep', 'spo2', 'heart', 'breathe'];

// 所有报告数据
const patientInfoArray: any = ref([]);
const getReportData = (visitNos: string) => {
  let params = {
    visitNos: visitNos,
    reportItems: printCheckList.join(","),
    reportDate: reportDate
  };
  printLoading.value = true;
  getMattressReportData(params).then((res: any) => {
    let data = res.data;
    for (let i = 0; i < data.length; i++) {
      let reportInfo = data[i];
      // 患者信息
      let patInfo = reportInfo.patInfo;
      patInfo.addr = getAddr(patInfo.province, patInfo.city, patInfo.district, patInfo.address);

      //报告数据
      printCheckList.forEach((val: any) => {
        if (sleepLabel == val) {
          let sleepData = reportInfo.sleepReportVo;
          patInfo.sleepChartData = reactive(sleepData);
          patInfo.sleepReportData = covertReport(val, sleepData);
        }
        if (spo2Label == val) {
          let spO2Data = reportInfo.spO2ReportVo;
          patInfo.spo2ChartData = reactive(spO2Data);
          patInfo.spo2ReportData = covertReport(val, spO2Data);
        }
        if (heartLabel == val) {
          let heartRateData = reportInfo.heartRateReportVo;
          patInfo.heartChartData = reactive(heartRateData);
          patInfo.heartReportData = covertReport(val, heartRateData);
        }
        if (breatheLabel == val) {
          let breatheData = reportInfo.breathRateReportVo;
          patInfo.breatheChartData = reactive(breatheData);
          patInfo.breatheReportData = covertReport(val, breatheData);
        }
      });
      patientInfoArray.value.push(patInfo);
    }

    printLoading.value = false;

  });
}

const covertReport = (type: string, data: any) => {
  let fmtData: any = [];

  // 睡眠
  if(sleepLabel == type) {
    fmtData = [{title: '时长'}, {title: '睡眠占比(%)'}];
    if (!data) {
      return fmtData;
    }
    fmtData = [
      {
        sleepTitle: "时长",
        sleepTotal: data.sleepDuration,
        lightSleepDuration: data.lightSleepDuration,
        deepSleepDuration: data.deepSleepDuration,
        getUpCount: data.getUpCount,
        wakeUpTimeStr: data.wakeUpTimeStr,
        awakeDuration: data.sleepWakingDuration,
        outBedDuration: data.outBedDuration,
        outBedTimeProp: recordTimeTotal(data.outBedDurationSource, data.outBedDurationSource + data.deepSleepDurationSource + data.lightSleepDurationSource),
        sleepTimeProp: recordTimeTotal(data.deepSleepDurationSource + data.lightSleepDurationSource, data.outBedDurationSource + data.deepSleepDurationSource + data.lightSleepDurationSource),//睡眠时长占比=记录时长/24小时
      },
      {
        sleepTitle: "睡眠占比(%)",
        sleepTotal: '100%',
        lightSleepDuration: recordTimeTotal(data.lightSleepDurationSource, data.deepSleepDurationSource + data.lightSleepDurationSource),//浅睡占比=记录时长/总睡眠时长
        deepSleepDuration: recordTimeTotal(data.deepSleepDurationSource, data.deepSleepDurationSource + data.lightSleepDurationSource),//深睡占比=记录时长/总睡眠时长
        awakeDuration: '-',
      }
    ];
  }

  // 血氧
  if (spo2Label == type) {
    fmtData = [{title: '%'}, {title: '次'}];
    if (!data) {
      return fmtData;
    }
    fmtData = [
      {
        title: '%',
        avgSpO2: data.avgSpO2 || "",
        highestSpO2: data.highestSpO2 || "",
        lowestSpO2: data.lowestSpO2 || "",
      },{
        title: '次',
        mildSpO2: data.mildSpO2,
        moderateSpO2: data.moderateSpO2,
        severeSpO2: data.severeSpO2
      }
    ];
  }

  // 心率
  if (heartLabel == type) {
    fmtData = [{
      title: 'bmp',
    }];
    if (!data) {
      return fmtData;
    }
    fmtData = [{
      title: 'bmp',
      avgHeartRate: data.avgHeartRate || "",
      highestHeartRate: data.highestHeartRate || "",
      lowestHeartRate: data.lowestHeartRate || "",
      rheartRate: data.rheartRate || "",
    }];
  }

  // 呼吸
  if (breatheLabel == type) {
    fmtData = [{
      title: 'rpm',
      breathLessThanFive: [],
    }];
    if (!data) {
      return fmtData;
    }
    fmtData = [{
      title: 'rpm',
      highestBreathRate: data.highestBreathRate || "",
      lowestBreathRate: data.lowestBreathRate || "",
      avgBreathRate: data.avgBreathRate || "",
      lessThanOrEqualFiveCount: data.lessThanOrEqualFiveCount || "",
      apneaTimes: data.apneaTimes || "",
      breathLessThanFive: data.lessThanOrEqualFiveData || [],
    }];
  }
  return fmtData;
}

const serialNumber = reactive({
  sleep: '', spo2: '', hr: '', breathe: '', sugg: ''
})
const toChinesNum = (num: any) => {
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  let unit = ["", "十", "百", "千", "万"];
  num = parseInt(num);
  let getWan = (temp: any) => {
    let strArr = temp.toString().split("").reverse();
    let newNum = "";
    for (let i = 0; i < strArr.length; i++) {
      newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
    }
    return newNum;
  }
  let overWan = Math.floor(num / 10000);
  let noWan: any = num % 10000;
  if (noWan.toString().length < 4) {
    noWan = "0" + noWan
  }
  return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}
const nextPageShow = () => {//转换中文排序
  let count = 0;
  if (printCheckList.find((val: any) => val == sleepLabel)) {
    ++ count;
    serialNumber.sleep = toChinesNum(count);
  }
  if (printCheckList.find((val: any) => val == spo2Label)) {
    ++ count;
    serialNumber.spo2 = toChinesNum(count);
  }
  if (printCheckList.find((val: any) => val == heartLabel)) {
    ++ count;
    serialNumber.hr = toChinesNum(count);
  }
  if (printCheckList.find((val: any) => val == breatheLabel)) {
    ++ count;
    serialNumber.breathe = toChinesNum(count);
  }

  ++ count;
  serialNumber.sugg = toChinesNum(count);
}
nextPageShow()

const is_print = ref(false);
/**
 * 打印按钮
 */
const doPrint = () => {
  let notPrintDoms = ['my-icon', 'isPrintSwitch'];
  if (!is_print.value) {
    notPrintDoms.push("lessThanFiveTxt");
    notPrintDoms.push("lessThanFiveTitle");
    notPrintDoms.push("lessThanFiveContents");
  }

  printJS({
    printable: 'printDom',
    type: 'html',
    showModal: true,
    modalMessage: '文件生成中，请稍后…',
    targetStyles: ['*'],
    maxWidth: 1080,
    font_size: 'auto',
    ignoreElements: notPrintDoms,// 打印HTML时忽略打印的内容，以字符串数组形式传入元素的id
    style: `@page {size:auto;margin:0 10mm;}body {zoom: 100%} @media print{@page {size:portrait}}`,
    onLoadingStart: function () {
      let el = document.getElementById("printDom");
      el?.setAttribute('style', 'margin: 0;transform: scale(0.98);-ms-transform: scale(0.98);-webkit-transform: scale(0.98);');
    },
    onLoadingEnd: function () {
      let el = document.getElementById("printDom");
      el?.setAttribute('style', 'margin: 0 10px;transform: scale(0.36);-ms-transform: scale(0.36);-webkit-transform: scale(0.36);');
    },
    onPrintDialogClose: function () {
      // 浏览器打印对话框关闭后执行的回调函数。
    },
    onError: function () {
      ElMessageBox.alert('打印出错了，请刷新重试！', '提示', {
        confirmButtonText: '关闭',
      });
    },
  });
}

const getAddr = (province: string, city: string, district: string, address: string) => {
  let finalAddr = "";
  if (province) {
    finalAddr += province;
  }
  if (city) {
    finalAddr += city;
  }
  if (district) {
    finalAddr += district;
  }
  if (address) {
    finalAddr += address;
  }
  return finalAddr ? finalAddr : "-";
}

const recordTimeTotal = (time:number, monitorTimeTotal:number) => {
  return 0 == time ? "0%" : ((time * 1000) / (monitorTimeTotal * 1000) * 100).toFixed(2) + "%";
}

const suggTxt = ref();
const getSugg = (event : any) => {
  let txt = "";
  if (suggTxt.value) {
    txt += suggTxt.value + "\n";
  }
  suggTxt.value = txt + event.target.innerText;
}

let flag = navigator.userAgent.match(
  /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
);
if (flag) {
  // 接收参数（加密的）
  let paramsBase64Str : any = route.query.ps;
  if (paramsBase64Str) {
    // 解密后的参数字符串
    let paramStr = Base64.decode(paramsBase64Str);
    // 参数列表
    let params = paramStr.split("&");
    let paramObject : any = {};
    // 遍历并拿到参数名、参数值
    for (let i = 0; i < params.length; i++) {
      let element = params[i];
      let pa = element.split("=");
      paramObject[pa[0]] = pa[1];
    }

    // 判断时效（1小时内有效）
    let time = paramObject.time;
    let nowMils = Date.now();
    if (nowMils - time > 60 * 60 * 1000) {
      ElMessageBox.alert('当前链接已失效！', '提示', {
        confirmButtonText: '关闭',
      });
    } else {
      // 登录会话
      let access_token = paramObject.access_token;
      if (access_token) {
        const {wsCache} = useCache()
        wsCache.set('token', access_token);
        // 患者ID
        let id = paramObject.id;
        if (id) {
          getReportData(id);
        } else {
          ElMessageBox.alert('缺失患者就诊号！', '提示', {
            confirmButtonText: '关闭',
          });
        }
      } else {
        ElMessageBox.alert('登录会话无效！', '提示', {
          confirmButtonText: '关闭',
        });
      }
    }
  } else {
    ElMessageBox.alert('缺失必要参数！', '提示', {
      confirmButtonText: '关闭',
    });
  }
} else {
  ElMessageBox.alert('请在手机浏览器打开！', '提示', {
    confirmButtonText: '关闭',
  });
}

</script>

<style>
body {
  overflow: auto;
}

.el-message-box {
  transform: scale(0.8);
  /* IE9及以上 */
  -ms-transform: scale(0.8);
  /* Safari及Chrome */
  -webkit-transform: scale(0.8);
}
</style>
<style lang="scss" scoped>
.PageNext {
  page-break-after: always;
  -ms-page-break-after: always;
  -webkit-page-break-after: always;
}

.print {
  width: 2rem;
  height: 2rem;
  cursor: pointer;
  z-index: 100;
  position: fixed;
  right: 1rem;
  top: 1rem;
}

#printDom {
  min-width: 67.5rem;
  margin: 0 10px;
  /* 比例缩放 */
  transform: scale(0.36);
  transform-origin: left top;
  /* IE9及以上 */
  -ms-transform: scale(0.36);
  -ms-transform-origin: left top;
  /* Safari及Chrome */
  -webkit-transform: scale(0.36);
  -webkit-transform-origin: left top;
}

/* 医院名称 */
.hospital-name {
  text-align: center;
  font-size: 1.875rem;
  font-weight: bold;
  margin-top: 1.25rem;
  margin-bottom: 0.625rem;
}

.hospital-subtitle {
  text-align: center;
  font-size: 1.25rem;
  font-weight: bold;
}

.report-time-txt {
  text-align: right;
  font-size: 18px;
  font-weight: bold;
  padding-right: 5%;
}

/* 患者基本信息 */
.patDetails {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .detail-title {
    width: 100%;
    color: var(--el-text-color-primary);
    font-size: 20px;
    font-weight: 700;
  }

  .info-items {
    width: 33.333333%;
    font-size: 20px;
    display: flex;
    align-content: center;
    font-weight: 400;
    line-height: 23px;
    margin-bottom: 5px;

    .info-items-label {
      min-width: 105px;
      color: var(--el-text-color-primary);
      font-weight: 500;
      text-align: left;

      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;

      span {
        color: transparent;
      }
    }

    .info-items-value {
      width: calc(100% - 100px);
      padding: 0 10px;
      border-bottom: 1px solid var(--el-text-color-primary);
      color: var(--el-text-color-regular);
      text-align: left;
    }
  }
}

.sleep-report {
  font-size: 20px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .sleep-report-items {
    width: 33.333333%;
    color: var(--el-text-color-primary);
  }
}

.my-report-table {
  display: flex;
  align-content: center;
  page-break-inside: avoid;

  .items {
    width: 20%;
    color: #666;
    font-weight: bold;
    font-size: 20px;
    border: 1px solid #909399;
    line-height: 23px;
    padding: 8px 12px;
    border-bottom: 0;
    border-right: 0;
  }

  .items:last-child {
    border-right: 1px solid #909399;
  }

  .items-contents {
    font-weight: normal;
    color: var(--el-text-color-primary);
  }

  .items-bottom {
    border-bottom: 1px solid #909399;
  }

  .items25 {
    width: 25%;
  }
}

.report-title {
  font-weight: 700;
  font-size: 20px;
}

.report_detail {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .info-items {
    width: 25%;
    display: flex;
    align-content: center;
    font-weight: 400;
    line-height: 23px;
    font-size: 14px;
    margin-bottom: 5px;

    .info-items-label {
      min-width: 80px;
      color: var(--el-text-color-primary);
      font-weight: 500;
      text-align: left;

      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;

      span {
        color: transparent;
      }
    }

    .info-items-value {
      width: calc(100% - 100px);
      padding: 0 10px;
      border-bottom: 1px solid var(--el-text-color-primary);
      color: var(--el-text-color-regular);
      text-align: left;
    }
  }

  .info-items-lg {
    width: 33.333333%;
    font-size: 20px;
  }
}

textarea {
  width: 100%;
  min-height: 100px;
  max-height: 100px;
  resize: none;
  border: 1px solid #909399;
}

.my-icon {
  position: relative;
  top: -100px;
  left: calc(100% - 20px);
  z-index: 999;
  cursor: pointer;
}

.sugg-datas {
  width: 100%;
}

.sugg-datas-item {
  font-size: 12px;
  cursor: pointer;
  line-height: 24px;
  padding: 0 10px;
  border-radius: 4px;
  border-bottom: 1px solid #eee;
}

.sugg-datas:first-child {
  border-top: 1px solid #eee;
}

.sugg-datas-item:hover {
  color: #409EFF;
  background-color: var(--el-color-primary-light-9);
}
</style>